package com.gsafety.libraryktx.widget

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.LinearLayout
import com.github.mikephil.charting.charts.PieChart
import com.github.mikephil.charting.data.PieData
import com.github.mikephil.charting.data.PieDataSet
import com.github.mikephil.charting.data.PieEntry
import com.github.mikephil.charting.formatter.ValueFormatter
import com.gsafety.libraryktx.R
import com.gsafety.libraryktx.bean.PieChartInfo
import java.util.*

/**饼图
 * @author : lj
 * @date : 2020/7/30 14:35
 */
class CommonPieChart @JvmOverloads constructor(context: Context,
                                               attrs: AttributeSet? = null,
                                               defStyleAttr: Int = 0) : LinearLayout(context,attrs,defStyleAttr) {
    var chart:PieChart?=null
    init {
        initview(attrs)
    }


    private fun initview(attrs:AttributeSet?){
        var view = LayoutInflater.from(context).inflate(R.layout.common_piechart_layout, this)
        chart=view.findViewById(R.id.chart_pie)
    }

    /**
     * 设置数据
     */
    fun setData(datas:MutableList<PieChartInfo>){
        var entries = ArrayList<PieEntry>()
        // add a lot of colors
        var colors = ArrayList<Int>()
        datas.forEach(){
            entries.add(it.entry)
            colors.add(it.color)
        }
        var pieDataSet = PieDataSet(entries, "")
        pieDataSet.colors=colors
        var pieData =PieData(pieDataSet)
        pieDataSet.valueFormatter=(object :ValueFormatter(){
            override fun getFormattedValue(value: Float): String {
                return value.toInt().toString()
            }
        })
        chart?.let {
            it.isRotationEnabled=false
            pieData.setValueTextSize(10f)
            pieData.setValueTextColor(context.resources.getColor(R.color.color_white))
            it.description.isEnabled=false
            it.legend.isEnabled=false
            it.data=pieData
            it.invalidate();

        }

    }
}